/*
 *@本JS功能：班级修改
 *@本js作者：杨锡君
 *@编写时间：2017年10月31日
 */
$(function() {
    var Alert1 = new Alert();
    var loading1 = new Loading();
    loading1.init();
    var confirm1 = new Confirm();
    var $addBtn = $(".classAddBtn");
    var $delBtn = $(".classDelBtn");
    var $className = $(".className");
    var $departNames = $("#departNames");
    var $profession = $("#profession");
    var $saveClass = $(".saveClass");
    var delList = [];
    var $publicCancleBtn = $(".publicCancleBtn");
    var classAddModel = "<div class=\"addClassBoxes\" value=\"3\">" +
        "<div class=\"classTec\">" +
        "<img class=\"classAddBtn fl\" src=\"pc/images/ico_classadd.png\" />" +
        "<img class=\"classDelBtn fr\" src=\"pc/images/ico_classdel.png\" />" +
        "</div>" +
        "<div class=\"rightMargin fl\">" +
        "<label class=\"fl labelRight\">添加课程:</label>" +
        "<select class=\"publicSelect course\">" +
        "<option value=\"0\">请选择</option>" +
        "</select>" +
        "</div>" +
        "<span class=\"clear\"></span>" +
        "<div class=\"rightMargin fl\">" +
        "<label class=\"fl labelRight\">选择教师:</label>" +
        "<select class=\"publicSelect tea\">" +
        "<option value=\"0\">请选择</option>" +
        "</select>" +
        "</div>" +
        "</div>";

    function classEditModel(opt) {
        var str = 	"<div courseid=" + opt.courseId + " stuorteaid=" + opt.stuorteaId + " classid=" + opt.classId + " class=\"addClassBoxes\" value=\"5\">" +
            "<div class=\"classTec\">" +
            "<img class=\"classAddBtn fl\" src=\"pc/images/ico_classadd.png\" />" +
            "<img class=\"classDelBtn fr\" src=\"pc/images/ico_classdel.png\" />" +
            "</div>" +
            "<div class=\"rightMargin fl \">" +
            "<span class=\"fl labelRight\">添加课程:</span>" +
            "<select title="+ opt.courseName +" style=\"background:#f6f6f6;cursor:not-allowed;\" disabled=\"disabled\" class=\"publicSelect course\">" +
            "<option value=" + opt.courseId + ">" + opt.courseName + "</option>" +
            "</select>" +
            "</div>" +
            "<span class=\"clear\"></span>" +
            "<div class=\"rightMargin fl \">" +
            "<span class=\"fl labelRight\">选择教师:</span>" +
            "<select title="+ opt.userName +" style=\"background:#f6f6f6;cursor:not-allowed;\"  disabled=\"disabled\"  class=\"publicSelect tea\">" +
            "<option value=" + opt.stuorteaId + ">" + opt.userName + "</option>" +
            "</select>" +
            "</div>";
        if(opt.classEndMark == 1){
            str+="<i style='font-size: 14px;right: -18px;position: absolute;top: 6px;color: #c80211;'>已结课</i>"
        }
        str+="</div>";
        return str;
    }

    var editClass = {
        init: function() {
            var self = this;
            maxLengthLimit.init("className");
            var json = JSON.stringify({
                "pageNow": 1,
                "pageSize": 10
            });
            $.ajax({
                type: "post",
                url: "getClassList",
                data: {
                    "jsonStr": json
                },
                async: true,
                success: function(msg) {
                    msg = JSON.parse(msg);
                    self.courseList = msg.courseList;
                    self.teacherList = msg.teacherList;
                    //					院系获取
                    $.map(msg.departMentList, function(opt) {
                        $departNames.append("<option value=" + opt.departmentId + " >" + opt.departmentName + "</option>");
                    });
                    //					院系联动
                    $departNames.change(function() {
                        var deppartmentId = $departNames.val();
                        self.departmentChange(deppartmentId);
                    });
                    //课程获取
                    $.map(self.courseList, function(opt) {
                        $(".course").append("<option value=" + opt.courseId + ">" + opt.courseName + "</option>");
                    });
                    //老师获取
                    $.map(self.teacherList, function(opt) {
                        $(".tea").append("<option value=" + opt.stuorteaId + ">" + opt.userName + "</option>");
                    });
                    self.initData(self.courseList, self.teacherList);
                },
                error:function () {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;
                }
            });
        },
        initData: function(courseList, teacherList) {
            var self = this;
            //			获取初始数据
            var classId = result.paramData.classId;
            var json = {
                "classId": classId
            };
            json = JSON.stringify(json);
            $.ajax({
                type: 'post',
                url: 'skipSaveClass',
                data: {
                    'jsonStr': json
                },
                success: function(msg) {
                    msg = JSON.parse(msg);
                    $className.val(msg.classList[0].className);
                    $className.attr("classid", msg.classList[0].classId);
                    $departNames.val(msg.classList[0].departmentId);
                    self.departmentChange(msg.classList[0]);
                    $profession.val(msg.classList[0].professionId);
                    var str = "";
                    if(msg.relationList.length!=0){
                        $.map(msg.relationList, function(opt) {
                            str += classEditModel(opt);
                        });
                        $(".classBox").append(str);
                    }else{
                        $(".classBox").html(classAddModel);
                        //课程获取
                        $.map(courseList, function(opt) {
                            $(".addClassBoxes:last>div:nth-of-type(2)>.course").append("<option value=" + opt.courseId + ">" + opt.courseName + "</option>");
                        });
                        //老师获取
                        $.map(teacherList, function(opt) {
                            $(".addClassBoxes:last>div:last>.tea").append("<option value=" + opt.stuorteaId + ">" + opt.userName + "</option>");
                        });

                    }
                    self.bindEvent(courseList, teacherList);
                    $(".classAddBtn").hide();
                    $(".classAddBtn:last").show();
                },
                error:function () {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;
                }
            });

        },
        bindEvent: function(courseList, teacherList) {
            var self = this;
            //			添加课程与教师
            $(".classAddBtn").off("click").click(function() {
                self.addClassEvent(courseList, teacherList);
            });
            //			删除
            $(".classDelBtn").off("click").click(function() {
                self.delClassEvent($(this),courseList,teacherList);
            });
            //			保存
            $saveClass.off("click").click(function() {
                var flag = self.verifications();
                if(flag) {
                    self.saveClassEvent();
                }

            });
            //取消
            $publicCancleBtn.click(function() {
                var json = JSON.stringify({
                    "pageName":"adminClassMana"
                });
                window.location.href = "skipPage?jsonStr="+json;
            });
        },
        saveClassEvent: function() {
            var addList = [];
            if($(".addClassBoxes").length == 1 && $(".course").val() == 0 && $(".tea").val() === "0"){

            }else{
                $.each($(".addClassBoxes[value='3']"), function(opt) {
                    var stu = $(this).children("div:last").children("select:first").val();
                    var cid = Number($(this).children("div:eq(1)").children("select:first").val());
                    addList.push({
                        "stuorteaId": stu,
                        "courseId": cid
                    });
                });
            }
            var className = $className.val();
            var professionId = Number($profession.val());
            var departmentId = Number($departNames.val());
            var json = {
                "className": className,
                "professionId": professionId,
                "departmentId":departmentId,
                "classId":result.paramData.classId,
                "addList": addList,
                "delList":delList
            };
            json = JSON.stringify(json);
            loading1.show();
            //执行异步提交表单
            $.ajax({
                type: 'post',
                url: 'saveClass',
                data: {
                    "jsonStr": json
                },
                success: function(msg) {
                    msg = JSON.parse(msg);
                    loading1.hide();
                    if(msg.result == "success") {
                        Alert1.content = "修改班级成功";
                        Alert1.success = function() {
                            var json = JSON.stringify({
                                "pageName":"adminClassMana"
                            });
                            window.location.href = "skipPage?jsonStr="+json;
                        };
                        Alert1.init();
                        Alert1.show();

                    } else {
                        Alert1.content = msg.failMsg;
                        Alert1.init();
                        Alert1.show();
                    }
                },
                error: function() {
                    Alert1.content = "提交失败！";
                    Alert1.init();
                    Alert1.show();
                }
            });
        },
        departmentChange: function(opt) {
            if(opt.deppartmentId != 0) {
                var json = {
                    "departmentId": opt.deppartmentId
                };
                json = JSON.stringify(json);
                $.ajax({
                    type: "post",
                    url: "getProfessionListByDepmentId",
                    data: {
                        "jsonStr": json
                    },
                    async: true,
                    success: function(msg) {
                        msg = JSON.parse(msg);
                        $profession.empty();
                        $profession.append("<option value=\"0\">请选择</option>");
                        if(msg.professionList != null && msg.professionList.length != 0) {
                            $.map(msg.professionList, function(opt) {
                                $profession.append('<option value ="' + opt.professionId + '">' + opt.professionName + '</option>');
                            });
                        }
                        $profession.val(opt.professionId);
                    },
                    error:function () {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;
                    }
                });
            }
        },
        verifications: function() {
            //			验证
            var self = this;
            var classNameVal = $className.val();
            if(classNameVal == "") {
                Alert1.content = "请输入班级名称";
                Alert1.init();
                Alert1.show();
                return false;
            }
            var flag = verification.spaceCode(classNameVal);
            var flags = verification.specialCode(classNameVal);
            if(flag != true) {
                Alert1.content = flag;
                $className.val("");
                Alert1.init();
                Alert1.show();
                return false;
            }
            if(flags != true) {
                Alert1.content = flags;
                $className.val("");
                Alert1.init();
                Alert1.show();
                return false;
            }
            var departMentSel = $departNames.val();

            if(departMentSel == 0) {
                Alert1.content = "请选择院系";
                Alert1.init();
                Alert1.show();
                return false;
            }
            var professionSel = $profession.val();

            if(professionSel == 0) {
                Alert1.content = "请选择专业";
                Alert1.init();
                Alert1.show();
                return false;
            }
            if($(".addClassBoxes").length == 1 && $(".course").val() == 0 && $(".tea").val() === "0"){
                return true;
            }else{
                var array2 = [];
                var s;
                var c;
                $.each($(".addClassBoxes"), function(opt) {
                    var stu = $(this).children("div:last").children("select:first").val();
                    var cid = Number($(this).children("div:eq(1)").children("select:first").val());
                    s = true;
                    c = true;
                    if(cid == 0) {
                        Alert1.content = "请将教师教课信息补充完整";
                        Alert1.init();
                        Alert1.show();
                        c = false;
                        return false;

                    }
                    if(stu === "0") {

                        Alert1.content = "请将教师信息补充完整";
                        Alert1.init();

                        Alert1.show();
                        s = false;
                        return false;

                    }

                    array2.push({
                        "stuorteaId": stu,
                        "courseId": cid
                    });
                });
                var yn = self.indexof(array2);
                if(yn == true) {
                    Alert1.content = "存在重复课程请修改";
                    Alert1.init();
                    Alert1.show();
                    return false;
                }
                if(s==true && c==true) {
                    return true;
                }
            }
        },
        indexof: function(arr) {

            var hash = {};
            for(var i in arr) {
                if(hash[arr[i].courseId])
                    return true;
                hash[arr[i].courseId] = true;
            }
            return false;

        },
        delClassEvent: function(obj,courseList,teacherList) {
            var self = this;
            if($(".addClassBoxes").length == 1) {
                if(obj.parents(".addClassBoxes").attr("value") == 5){

                    delList.push({ "classId": obj.parents(".addClassBoxes").attr("classid"), "stuorteaId": obj.parents(".addClassBoxes").attr("stuorteaid"), "courseId": obj.parents(".addClassBoxes").attr("courseid") });
                }
                $(".classBox").html(classAddModel);
                //课程获取
                $.map(courseList, function(opt) {
                    $(".addClassBoxes:last>div:nth-of-type(2)>.course").append("<option value=" + opt.courseId + ">" + opt.courseName + "</option>");
                });
                //老师获取
                $.map(teacherList, function(opt) {
                    $(".addClassBoxes:last>div:last>.tea").append("<option value=" + opt.stuorteaId + ">" + opt.userName + "</option>");
                });

//				$(".classAddBtn").hide();
//				$(".classAddBtn:last").show();
            }else{
//				$(".classAddBtn").off("click").click(function() {
//				self.addClassEvent(courseList, teacherList);
//				});
//				//			删除
//				$(".classDelBtn").off("click").click(function() {
//					self.delClassEvent($(this),courseList,teacherList);
//				});
                if(obj.parents(".addClassBoxes").attr("value") == 5){

                    delList.push({ "classId": obj.parents(".addClassBoxes").attr("classid"), "stuorteaId": obj.parents(".addClassBoxes").attr("stuorteaid"), "courseId": obj.parents(".addClassBoxes").attr("courseid") });
                }
                obj.parents(".addClassBoxes").remove();

            }
            $(".classAddBtn").off("click").click(function() {
                self.addClassEvent(courseList, teacherList);
            });
            //			删除
            $(".classDelBtn").off("click").click(function() {
                self.delClassEvent($(this),courseList,teacherList);
            });
            $(".classAddBtn").hide();
            $(".classAddBtn:last").show();


//			$(".addClassBoxes:last").remove();
        },
        addClassEvent: function(courseList, teacherList) {

            var self = this;

            $(".classBox").append(classAddModel);
            $(".classAddBtn").off("click").click(function() {
                self.addClassEvent(courseList, teacherList);

            });
            //			删除
            $(".classDelBtn").off("click").click(function() {
                self.delClassEvent($(this),courseList, teacherList);
            });
            //课程获取
            $.map(courseList, function(opt) {
                $(".addClassBoxes:last>div:eq(1)>.course").append("<option value=" + opt.courseId + ">" + opt.courseName + "</option>");
            });
            //老师获取
            $.map(teacherList, function(opt) {
                $(".addClassBoxes:last>div:last>.tea").append("<option value=" + opt.stuorteaId + ">" + opt.userName + "</option>");
            });
            $(".classAddBtn").hide();
            $(".classAddBtn:last").show();
        }
    };
    editClass.init();
});